package com.diamond.util;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;



public class ChineseFilter implements Filter {
    private FilterConfig filterConfig;
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    /**
     * 解决中文问题.（对于post方法提交的请求适用）
     * 
     */
    public void doFilter(ServletRequest request, ServletResponse response,FilterChain filterChain) {
        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            HttpServletRequest req = (HttpServletRequest) request;
            HttpServletResponse res = (HttpServletResponse)response;
            String path = ((HttpServletRequest)request).getServletPath();
            HttpSession session = req.getSession();
            if(path.startsWith("/images/")||path.equals("/index.jsp")||path.equals("/login.jsp")||path.equals("/admin.do")||path.equals("/adminAction")){
				filterChain.doFilter(request, response);
            }else{
				if (session.getAttribute("userId") == null) {
					res.sendRedirect(req.getContextPath() + "/login.jsp");
				} else {
					//可在此控制已经登录过的用户的权限
					filterChain.doFilter(request, response);
				}
            }
            
        } catch (Exception iox) {
            filterConfig.getServletContext().log(iox.getMessage());
        }
    }

    public void destroy() {
    }
}
